import { reactive } from "vue";
import type { FormRules } from "element-plus";
import { checkDictCode } from "@/api/system";

/** 自定义表单规则校验 */
export const formRules = reactive(<FormRules>{
  name: [
    { required: true, message: "权限名称为必填项", trigger: "blur" },
    { max: 50, message: "权限名称不能超过50字", trigger: "blur" }
  ],
  code: [
    { required: true, message: "权限编码为必填项", trigger: "blur" },
    { max: 50, message: "权限编码不能超过50字", trigger: "blur" },
    {
      validator: async (_, value, callback) => {
        if (value === "") {
          callback(new Error("权限编码为必填项"));
        } else {
          await checkDictCode(value)
            .then(res => {
              if (!res) {
                callback(new Error("权限编码已存在"));
              } else {
                callback();
              }
            })
            .catch(() => {
              callback(new Error("权限编码已存在"));
            });
        }
      },
      message: "权限编码已存在",
      trigger: "blur"
    }
  ],
  description: [{ max: 200, message: "权限描述不能超过200字", trigger: "blur" }]
});
